package org.crag.cafca.logic.time;

import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;

import org.crag.cafca.logic.time.Tag;
import org.joda.time.DateTime;


public abstract class Event 
{
	private long id;
	private String description;
	private Set<Tag> tags;
	private DateTime startDateTime;
	private DateTime endDateTime;
	private String value;
	private TimeLine timeLine;
	
	private static Comparator<Event> eventsComparator;
	
	static
	{
		eventsComparator=new Comparator<Event>() 
		{
			@Override
			public int compare(Event o1, Event o2) 
			{
				if(o1.getStartDateTime().isBefore(o2.getStartDateTime()))
					return -1; 
				else if (o1.getStartDateTime().isAfter(o2.getStartDateTime()))
					return 1; 
				else 
					return 0;
			}
		};	
	}

	public static Comparator<Event> getEventsComparator() 
	{
		return eventsComparator;
	} 
	

	public Event()
	{
		this.tags=new HashSet<Tag>();
		this.description="";
		this.value="";
	}	

	public long getId() 
	{
		return id;
	}

	public void setId(long id) 
	{
		this.id=id;
	}	

	public boolean containsTag(Tag tag)
	{
		return tags.contains(tag);
	}
	
	public void addTag(Tag tag)
	{
		this.tags.add(tag);
	}
	
	public void removeTag(Tag tag)
	{
		this.tags.remove(tag);
	}
	
	public void clearTags()
	{
		this.tags.clear();
	}

	public DateTime getStartDateTime() 
	{
		return startDateTime;
	}

	public void setStartDateTime(DateTime startDateTime) 
	{
		this.startDateTime = startDateTime;
	}

	public DateTime getEndDateTime() 
	{
		return endDateTime;
	}

	public void setEndDateTime(DateTime endDateTime) 
	{
		this.endDateTime = endDateTime;
	}
	
	public void setDescription(String description)
	{
		this.description=description;
	}
	
	public String getDescription()
	{
		return description;
	}
	
	public boolean isInstantaneous()
	{
		if (this.startDateTime.equals(this.endDateTime))
			return true;
		else
			return false;
	}

	public String getValue() 
	{
		return value;
	}

	public void setValue(String value) 
	{
		this.value = value;
	}
	
	public Set<Tag> getTags() 
	{
		return tags;
	}
	
	public String toString()
	{
		return "id="+id+", startTime="+startDateTime+", endTime="+endDateTime+", value="+value+", tags=[]";
	}
	
	public String getTagString()
	{
		StringBuffer result=new StringBuffer();
		
		int counter=0;
		for (Tag tag:tags)
		{
			result.append(tag.getName());
			
			if (counter<tags.size()-1)
				result.append(";");
			
			counter++;
		}
		
		return result.toString();
	}

	public void addTags(String tagString)
	{
		String[] tokens=tagString.split(";");
		for (String token:tokens)
		{
			tags.add(new Tag(token));
		}
	}

	public TimeLine getTimeLine() 
	{
		return timeLine;
	}

	public void setTimeLine(TimeLine timeLine) 
	{
		this.timeLine = timeLine;
	}
}
